/**
 * Created by Administrator on 2017/3/13.
 */
$('iframe').remove();
//获取url参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]); return null;
}
//页面加载完毕后隐藏loading
window.onload=function(){
    $('.weui-loadmore').css('display','none')
};

//向前后几天
function ktkGetNextDate(AddDayCount)
{
    var dd = new Date();
    dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
    var y = dd.getYear();
    var m = dd.getMonth()+1;//获取当前月份的日期
    var d = dd.getDate();
    d = d < 10 ? ('0' + d) : d;
    m = m < 10 ? '0' + m : m;
    return m+"-"+d;
}


//底部导航
$('#footer').on('click','li',function(){
    if($(this).hasClass('gouwuche')){
        ajaxCarList();
        $('#cartDetails').slideDown();
    }else if($(this).hasClass('jishi')) {
        //跳转我的技师 解决local获取不到
        var local=JSON.parse(sessionStorage.getItem('location'))||{latitude:'',longitude:''};
        location.href=personnelUrl+'localLat='+local.latitude+'&localLon='+local.longitude;
    }else{
        location.href = $(this).data('href');
    }
});
//跳转支付页面
$('#cartDetails a:last-child').click(function(){
    if($('#footer .gouwuche b').html()=='0'){
        return false;
    }
    location.href=urlorder;
});
/**
 * index.html
 * personnelListDetail.html
 * **/
//隐藏购物车 继续选购
function continueBuy(){
   $('#cartDetails').slideUp();
}

//加载购物车数据
function ajaxCarList(){
    $.post(ajaxCar,function(res){
      var data=JSON.parse(res);
      if(data.length==0){return false;}
      var html='';
      for(var i=0;i<data.length;i++){
          var timeS=data[i].starttime;
        html+='<div><h5>'+data[i].title+'<i data-price='+data[i].oprice+' data-jishiid='+data[i].jishi_id+' data-storeid='+data[i].store_id+' data-id='+data[i].id+' data-addressid='+data[i].address_id+' data-startt="'+timeS+'" class="minus iconal-roundclosefill" onclick="listsMinus(this)"></i></h5>' +
        '<p>'+data[i].jishi.nickname+'</p><p>'+(timeS).slice(5)+'</p>'+
        '<p><span>￥'+data[i].price+'</span>' +
        '</p></div>';
      }
      $('.cart_lists').html(html);
    })
}
//更新购物车
function updateCart(){
    $.post(ajaxCar,function(res){
        var data=JSON.parse(res);
        if(data.length==0){
            $('#footer .gouwuche b').html(0);
            sessionStorage.setItem('sessCart','');
            return false;
        }
        var num= 0,times= 0,prices= 0,sessCart='';
        for(var i=0;i<data.length;i++){
            num+=data[i].num-0;
            times+=Number(data[i].num)*Number(data[i].item_endtime);
            prices+=Number(data[i].num)*Number(data[i].oprice);
            sessCart+=data[i].id+data[i].store_id+data[i].address_id+data[i].starttime+data[i].jishi_id+','
        }
        $('#footer .gouwuche b').html(num);
        sessionStorage.setItem('sessCart',sessCart);
    })
}
//购物车减
function listsMinus(self){
    $.get(
        minusCar,
        {
            id:$(self).attr('data-id'),
            storeid:$(self).attr('data-storeid'),
            addressid:$(self).attr('data-addressid'),
            timeS:$(self).attr('data-startt'),
            jishiid:$(self).attr('data-jishiid')
        },
        function(data){
            if (data == 1) {
                $(self).parent().parent().remove();
                $('#footer .gouwuche b').html($('#footer .gouwuche b').html()-1);
                updateCart();
            }else{
                $.toast('删除失败','text');
            }
        }
    );
}
//购物车加
function listsAdd(self){
    $.get(
        addCar,
        {id:$(self).prev().attr('data-id')},
        function(data) {
            if (data == 1) {
                $(self).prev().html($(self).prev().html()-0+1);
                $('.iconal-gouwuche>b').html($('.iconal-gouwuche>b').html()-0+1);
                $('.cartSum_num>p:first-child>span').html($('.iconal-gouwuche>b').html());
                $('.cartSum_num>p:last-child>span').html($('.cartSum_num>p:last-child>span').html()-0+Number($(self).prev().attr('data-time')));
                var price=$('.cartSum_price>b').html()-0+($(self).prev().attr('data-price')-0);
                $('.cartSum_price>b').html(price.toFixed(2));
            }
        }
    )
}
//清空购物车
function clearCart(){
    if($('#footer .gouwuche b').html()=='0'){         
        return false;
    }
    $.confirm("确定删除所有项目?", function() {
        $.get(clearCartList,function(data){
            if(data==1){
                $('.iconal-gouwuche>b').html(0);
                $('.cart_lists').html('');
                updateCart();
            }
        })
    }, function() {
        //点击取消后的回调函数
    });
}


//客服二维码
$('a.kefu').click(function(){
    $('.kefuEWM').css('display','block');
});
$('.kefuEWM').click(function(){
    $(this).css('display','none');
});

//打开优惠券列表
function openCoupon(){
    $.toast('暂无可用优惠券','text');
    $('#COUPON').load('coupon.html').slideDown();
}
//打开地址列表
function ajaxAdd(){
    $.get(ajaxAddress,function(res){
        var data=JSON.parse(res);
        console.log(data);
        var html='';
        for(var i=0;i<data.length;i++){
            var htmlactive='';
            data[i].status=='1'?htmlactive='active':'';
            html+='<div><div class="list_name"><span>'+data[i].cname+'</span><span>'+data[i].tel+'</span></div>' +
            '<div class="list_add"><i class="iconal-roundcheckfill '+htmlactive+'"></i>' +
            '<span class="SSQ">'+data[i].province+data[i].city+data[i].county+'</span></div>' +
            '<div style="margin-left:50px"><span>'+data[i].detailed_address+'</span></div>'+
            '<div data-id='+data[i].id+' class="list_handle">' +
            '<a onclick="chooseXZ(this)" href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary">选择</a>' +
            '<a onclick="chooseBJ(this)" href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary middelBtn" data-status='+data[i].status+'>编辑</a>' +
            '<a onclick="chooseSC(this)" href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary">删除</a> </div></div>'
        }
        $('.address_list').html(html);
        $('#address').slideDown();
    })
}
function closeADDList(){
    $('#address').slideUp();
}
function closeADDEdit(){
    $.get(addressmoren, function (res) {
        var data = JSON.parse(res);
        if (!data.id) {
            $('.MDorSM').html('<a onclick="ajaxAdd(this)" class="weui-cell weui-cell_access" href="javascript:;">' +
            '<div class="weui-cell__bd weui-cell_primary"><p>请填写地址信息</p></div><span class="weui-cell__ft"></span></a>');
        }
    });
    $('#addAddress').slideUp();
}
$("#cityPicker").cityPicker({
    title: "选择地区",
    onChange: function (picker, values, displayValues) {
        console.log(values, displayValues);
    }
});

function openAdd(){//新增地址
    $('.switch').html('<input onclick="switcha(this)" class="weui-switch" type="checkbox" value="0">');
    $('#addAddress').slideDown();
}
$('.address_btn>a').click(function(){//保存地址
    var myname=$('input.nameadd').val();
    var myphone=$('input.tel').val();
    var cityPicker=$('#cityPicker').val();
    var district=$('input.address').val();
    var status=$('input.weui-switch').val();
    if(myname==""){
        $.toast('请输入姓名','cancel');
        return false;
    }
    if(myphone==""){
        $.toast('请输入电话','cancel');
        return false;
    }
    if(cityPicker==""){
        $.toast('请选择地区','cancel');
        return false;
    }
    if(district==""){
        $.toast('请输入详细地址','cancel');
        return false;
    }
    $.get(
        addressEdit,
        {
            "id": $('.address_btn').attr('data-id')||'',
            "myname": myname,
            "myphone": myphone,
            "province": cityPicker.split(' ')[0],
            "city": cityPicker.split(' ')[1],
            "county": cityPicker.split(' ')[2],
            "detailed": district,
            "status": Number(status)%2
        },function(res) {
            var data=JSON.parse(res);
            if(data.status=='1'){
                $.toast('保存成功');
                setTimeout(function(){$('#addAddress').slideUp();},2000);
                ajaxAdd();
                $('input.weui-switch').val('0');
                $('#cityPicker').val('');
            }else{
                $.toast('保存失败','forbidden');
                return false;
            }
        }
    );
});
//是否默认
function switcha(self){
    $(self).val($(self).val()-0+1);
}
function chooseXZ(e){
    $('#address').slideUp();
    var html='<p>'+$(e).parent().prev().prev().prev().children("span:first-child").html()+'  '+$(e).parent().prev().prev().prev().children("span:last-child").html()+
        '</p><p>'+$(e).parent().prev().prev().find('span.SSQ').html()+'</p><p>'+$(e).parent().prev().find('span').html()+'</p>';
    $('.MDorSM').attr('data-addid',$(e).parent().attr('data-id')).attr('data-addressid',$(e).parent().attr('data-id')).find('div.weui-cell__bd').html(html);
}
function chooseBJ(e){
    $('input.nameadd').val($(e).parent().prev().prev().prev().find('span:first-child').html());
    $('input.tel').val($(e).parent().prev().prev().prev().find('span:last-child').html());
    $('input.address').val($(e).parent().prev().find('span:last-child').html());
    $('.address_btn').attr('data-id',$(e).parent().attr('data-id'));
    console.log($(e).attr('data-status'))
    if($(e).attr('data-status')=='0'){
        $('.switch').html('<input onclick="switcha(this)" class="weui-switch" type="checkbox" value="0">')
    }else{
        $('.switch').html('<input onclick="switcha(this)" class="weui-switch" type="checkbox" value="1" checked>')
    }

    $('#addAddress').slideDown();
}
function chooseSC(e){
    $.confirm("确定删除地址?", function() {
        $.get(
            addressDel,
            {id:$(e).parent().attr('data-id')},
            function(res){
                var data=JSON.parse(res);
                if(data.status=='1'){
                    $.toast('删除成功');
                    ajaxAdd();
                }
            }
        )
    }, function() {
        //点击取消后的回调函数
    });
}

//选择地址
function addressCH(e){
    //$('.address_top').attr('data-addid','.address'+$(e).attr('data-id'));
    ajaxAdd();
}
//进行经纬度转换为距离的计算

function Rad(d){
    return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
}
//计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
function GetDistance(lat1,lng1,lat2,lng2){

    var radLat1 = Rad(lat1);
    var radLat2 = Rad(lat2);
    var a = radLat1 - radLat2;
    var  b = Rad(lng1) - Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
    var ss="";
    s = s *6378.137 ;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000; //输出为公里
    //s=s.toFixed(4);
    if(s>=3){
        ss= s.toFixed(2)+' 公里';
    }else{
        ss=(s*1000).toFixed(0)+' 米'
    }
    return ss;
}



